
#include "ScriptThread.h"

ScriptThread::ScriptThread(BScript* script)
{
	_tick = 0;
	this->setScript(script);
}
ScriptThread::~ScriptThread()
{
	if (_script)
	{
		disconnect(_script);
	}
}

bool ScriptThread::setScript(BScript* script)
{
	if (_script != script)
	{
		if (_script)
		{
			disconnect(_script);
		}
		_script = script;
		if (_script)
		{
			connect(_script, Signal_Performed, &ScriptThread::slotScriptPerformed);
		}
		return true;
	}
	return false;
}
BScript* ScriptThread::script()
{
	return _script;
}

void ScriptThread::setup(const BString& funcName, const BValueArray& params)
{
	_funcName = funcName;
	_params = params;
}

void ScriptThread::slotScriptPerformed(BObject* object, const BValue& value)
{
	_runInfo.counter = value;
	_runInfo.stackSize = _script->stackSize();
	_runInfo.stackCapacity = _script->stackCapacity();
	BReal now = bTime();
	if (now - _tick > 0.5)
	{
		_tick = now;
		this->post("run-info", _runInfo);
	}
}

int ScriptThread::run()
{
	if (_script->error())
		return 1;
	_script->call(_funcName, _params.size(), _params.data());
	return 0;
}
